#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: bk201
# @Date:   2015-10-09 11:07:31
# @Last Modified by:   bk201
# @Last Modified time: 2015-10-10 11:33:33
# this py only tested by python 3.5
import sys
import os
import re
import urllib
import http.cookiejar
from bs4 import BeautifulSoup
'''
    写log文件
'''
def writeLog(logName,logContent):
    shell_path = sys.path[0]
    log = "%s/log"%shell_path
    if not os.path.exists(log):
        os.mkdir(log) 
    save_path="%s/log/%s.log"%(shell_path,logName)
    f_obj = open(save_path,'wb')  
    f_obj.write(logContent)
    
''' 
   v2ex自动签到 
'''
def v2exGetCoin(username,passwd):
    #初始设置
    login_url = "https://www.v2ex.com/signin"
    index_url = "https://www.v2ex.com/"
    daily_url = "https://www.v2ex.com/mission/daily"
    #设置一个cookie处理器，它负责从服务器下载cookie到本地，并且在发送请求时带上本地的cookie
    cj=http.cookiejar.LWPCookieJar()
    cookie_support = urllib.request.HTTPCookieProcessor(cj)
    opener = urllib.request.build_opener(cookie_support,urllib.request.HTTPHandler)
    urllib.request.install_opener(opener)
    #使用BeautifulSoup解析页面获取once值(类似token值) 
    response = urllib.request.urlopen(login_url)
    loginHtml = response.read()
    soup = BeautifulSoup(loginHtml,"html.parser")
    once = soup.find('input',attrs={'name':'once', 'type':'hidden'})
    onceVal = once["value"]
    #登录
    #构造header，一般header至少要包含一下两项。
    headers = {'User-Agent' : ' Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.7) Gecko/20150929 Firefox/31.9 PaleMoon/25.7.2',  
           'Referer' : login_url}
    #构造登录post
    postData = {'next':'/','once':onceVal,'p':passwd,'u':username}
    postData = urllib.parse.urlencode(postData).encode('utf-8')       
    request = urllib.request.Request(login_url,postData,headers)
    response = urllib.request.urlopen(request)  
    indexHtml = response.read();
    # #分析是否登录成功
    # if not index_url==response.url:
    #     print ("===v2ex login failed===")
    #     writeLog("v2ex_login_failed",indexHtml)
    #     return False
    # #get coin
    # headers = {'User-Agent' : ' Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.7) Gecko/20150929 Firefox/31.9 PaleMoon/25.7.2',  
    #        'Referer' : daily_url}   
    # request = urllib.request.Request(daily_url,headers=header)
    # response = urllib.request.urlopen(request)
    # getCoinHtml = response.read()
    # soup = BeautifulSoup(getCoinHtml,"html.parser")
    # onceVal = re.findall(r"(?<=\bonce=)\w+\b",str(soup))[0] 
    # get_coin_url = "%s/redeem?once=%s"%(daily_url,onceVal)
    # headers = {'User-Agent' : ' Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.7) Gecko/20150929 Firefox/31.9 PaleMoon/25.7.2',  
    #        'Referer' : get_coin_url}   
    # request = urllib.request.Request(get_coin_url,headers=header)
    # response = urllib.request.urlopen(request)
    # #分析是否获取成功
    # onceVal = re.findall(r"(?<=\bonce=)\w+\b",str(soup))
    # if  len(onceVal)<2:
    #     print ("===v2ex get coin failed===")
    #     writeLog("v2ex_coin_failed",getCoinHtml)
    #     return False
    # return True